// check_existing_transactions.js
// 检查已存在的银行流水记录

const SequelizeLib = require('sequelize');

// 数据库配置（使用项目中的配置）
const sequelize = new SequelizeLib({
  dialect: 'mysql',
  host: '127.0.0.1',
  port: 3306,
  username: 'root',
  password: '888mei525',
  database: 'lingxi_system',
  logging: false
});

// 银行流水模型
const BankTransactionModel = sequelize.define('bankTransaction', {
  id: {
    type: SequelizeLib.DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  organizationId: {
    type: SequelizeLib.DataTypes.INTEGER,
    allowNull: false,
    field: 'organization_id'
  },
  transactionId: {
    type: SequelizeLib.DataTypes.STRING(200),
    allowNull: false,
    unique: true,
    field: 'transaction_id'
  },
  payerName: {
    type: SequelizeLib.DataTypes.STRING(200),
    allowNull: false,
    field: 'payer_name'
  },
  payerAccount: {
    type: SequelizeLib.DataTypes.STRING(100),
    field: 'payer_account'
  },
  amount: {
    type: SequelizeLib.DataTypes.DECIMAL(12, 2),
    allowNull: false
  },
  transactionDate: {
    type: SequelizeLib.DataTypes.DATE,
    allowNull: false,
    field: 'transaction_date'
  },
  transactionTime: {
    type: SequelizeLib.DataTypes.DATE,
    allowNull: false,
    field: 'transaction_time'
  },
  balance: {
    type: SequelizeLib.DataTypes.DECIMAL(12, 2)
  },
  remark: {
    type: SequelizeLib.DataTypes.TEXT
  },
  dataSource: {
    type: SequelizeLib.DataTypes.ENUM('file_import', 'plugin_capture'),
    defaultValue: 'file_import',
    field: 'data_source'
  },
  importBatch: {
    type: SequelizeLib.DataTypes.STRING(100),
    field: 'import_batch'
  },
  isFiltered: {
    type: SequelizeLib.DataTypes.BOOLEAN,
    defaultValue: false,
    field: 'is_filtered'
  },
  filterReason: {
    type: SequelizeLib.DataTypes.STRING(100),
    field: 'filter_reason'
  },
  createdAt: {
    type: SequelizeLib.DataTypes.DATE,
    field: 'created_at'
  },
  bankName: {
    type: SequelizeLib.DataTypes.STRING(200),
    field: 'bank_name'
  },
  currency: {
    type: SequelizeLib.DataTypes.STRING(50)
  },
  channel: {
    type: SequelizeLib.DataTypes.STRING(50)
  },
  fee: {
    type: SequelizeLib.DataTypes.DECIMAL(12, 2),
    defaultValue: 0
  },
  accountName: {
    type: SequelizeLib.DataTypes.STRING(200),
    field: 'account_name'
  },
  accountNumber: {
    type: SequelizeLib.DataTypes.STRING(100),
    field: 'account_number'
  }
}, {
  tableName: 'bank_transactions',
  timestamps: false
});

// 检查已存在的银行流水记录
async function checkExistingTransactions() {
  try {
    console.log('🔍 连接数据库...');
    await sequelize.authenticate();
    console.log('✅ 数据库连接成功!');
    
    // 检查是否存在相同的流水号
    const existing = await BankTransactionModel.findOne({
      where: {
        transactionId: '20251121R9989895'
      }
    });
    
    if (existing) {
      console.log('🔍 找到已存在的流水记录:');
      console.log(`  流水号: ${existing.transactionId}`);
      console.log(`  金额: ${existing.amount}`);
      console.log(`  交易日期: ${existing.transactionDate}`);
      console.log(`  数据来源: ${existing.dataSource}`);
    } else {
      console.log('✅ 流水号 20251121R9989895 不存在');
    }
    
    // 查询最近的几条记录
    const recentTransactions = await BankTransactionModel.findAll({
      order: [['transactionDate', 'DESC']],
      limit: 5
    });
    
    console.log(`\n📊 最近的 ${recentTransactions.length} 条银行流水记录:`);
    recentTransactions.forEach((transaction, index) => {
      console.log(`  ${index + 1}. ${transaction.transactionId} - ${transaction.amount} - ${transaction.transactionDate}`);
    });
    
    // 统计总记录数
    const totalCount = await BankTransactionModel.count();
    console.log(`\n📈 银行流水总记录数: ${totalCount}`);
    
  } catch (error) {
    console.error('❌ 检查已存在的银行流水记录失败:', error.message);
    throw error;
  } finally {
    await sequelize.close();
  }
}

// 主函数
async function main() {
  try {
    console.log('🚀 开始检查已存在的银行流水记录...');
    await checkExistingTransactions();
    console.log('✅ 检查完成!');
  } catch (error) {
    console.error('❌ 检查失败:', error.message);
    process.exit(1);
  }
}

// 执行主函数
if (require.main === module) {
  main();
}

module.exports = {
  checkExistingTransactions
};